package com.ganbo.pattern.test;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import java.lang.reflect.Method;

/**
 * 1：定义目标对象
 */
class Car {

    public String drive(String name) {
        System.out.println(name + "正在开车....");
        return "success";
    }
}

/**
 * 2：编写代理工具类
 */
public class CglibDynimicProxy implements MethodInterceptor {

    private Object target;

    /**
     * 构造方法传入目标对象
     */
    public CglibDynimicProxy(Object target) {
        this.target = target;
    }

    /**
     * 获取代理对象(这里基本上是固定写法)
     */
    public Object getInstance() {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(target.getClass());
        enhancer.setCallback(this);
        return enhancer.create();
    }

    public Object intercept(Object o, Method method, Object[] params, MethodProxy methodProxy) throws Throwable {
        long start = System.currentTimeMillis();
        System.out.println("准备开车");
        Object invoke = methodProxy.invokeSuper(o, params); //调用父类方法
        System.out.println("结束开车,营养跟不上了。开车时长:" + (System.currentTimeMillis() - start) + "毫秒。");
        return invoke;
    }


    //测试
    public static void main(String[] args) {
        Car car = new Car(); //创建目标对象
        CglibDynimicProxy proxy = new CglibDynimicProxy(car); //获取代理对象
        Car carProxy = (Car) proxy.getInstance();
        carProxy.drive("隔壁老王");
    }
}
